//
//  MyTicketViewController.m
//  myhuibao
//
//  Created by 孙昕 on 14-3-12.
//  Copyright (c) 2014年 myhuibao. All rights reserved.
//

#import "MyTicketViewController.h"
#import "SBJson.h"
#import "ASIHTTPRequest.h"
#import "Config.h"
#import "MyTicketCell.h"
#import "TicketDetailViewController.h"
#import "LoadMoreCell.h"
#import "OMGToast.h"
#import "LeveyPopListView.h"

@interface MyTicketViewController ()

@end

@implementation MyTicketViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    pageIndex=1;
    arrayType = [NSMutableArray arrayWithObjects:
                    [NSDictionary dictionaryWithObjectsAndKeys:@"全部",@"arrayType",nil],
                    [NSDictionary dictionaryWithObjectsAndKeys:@"代金券",@"arrayType",nil],
                    [NSDictionary dictionaryWithObjectsAndKeys:@"折扣券",@"arrayType",nil],
                    [NSDictionary dictionaryWithObjectsAndKeys:@"返券",@"arrayType",nil],
                    [NSDictionary dictionaryWithObjectsAndKeys:@"返还代金券",@"arrayType",nil],
                    nil];
    arrayStatus = [NSMutableArray arrayWithObjects:
                 [NSDictionary dictionaryWithObjectsAndKeys:@"未使用",@"arrayStatus",nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:@"已使用",@"arrayStatus",nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:@"已过期",@"arrayStatus",nil],
                   nil];
    arrayMerchantType = [NSMutableArray arrayWithObjects:
                   [NSDictionary dictionaryWithObjectsAndKeys:@"全部商户",@"arrayMerchantType",nil],
                   [NSDictionary dictionaryWithObjectsAndKeys:@"餐饮",@"arrayMerchantType",nil],
                   [NSDictionary dictionaryWithObjectsAndKeys:@"KTV",@"arrayMerchantType",nil],
                   [NSDictionary dictionaryWithObjectsAndKeys:@"咖啡茶馆",@"arrayMerchantType",nil],
                   nil];
    
    
    [self getMyTicket];
    // Do any additional setup after loading the view from its nib.
}

-(void)getMyTicket
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?memberID=%d&password=%@&couponType=%d&status=%d&merchantType=%d&pageIndex=%d",url_myTicketList,[[Config Instance] getMemberId],[[Config Instance] getPassword] ,couponType,status,merchantType,pageIndex]];
    ASIHTTPRequest *req = [ASIHTTPRequest requestWithURL:url];
    [req setShouldAttemptPersistentConnection:NO];
    [req setDelegate: self];
    [req setDidFinishSelector:@selector(finishGetTicket:)];

    [req startAsynchronous];

}

-(void)finishGetTicket:(ASIHTTPRequest*)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    
    tableDataArray = [dic valueForKey:@"data"];
    if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"])
    {
        if ([dic valueForKey:@"data"]==[NSNull null]) {
            [OMGToast showWithText:search_empty_msg bottomOffset:100];
            tableDataArray=nil;
        }
        else
        {
            returnCount = [tableDataArray count];
        }
        if (returnCount==0) {
            [OMGToast showWithText:search_empty_msg bottomOffset:100];
        }

        [_TicketTable reloadData];
    }
    [Config setExtraCellLineHidden:_TicketTable];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    int count = [tableDataArray count];
    if (count>=pageSize || rowCount-2==count ) {
        rowCount=count+1;
        return count+1;
    }
    else
    {
        rowCount=count;
        return count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] < ([tableDataArray count])) {
        return 80;
    }else{
        return 40;
    }
}

- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"MyTicketCellIdentifier";
     if([indexPath row] < ([tableDataArray count]))
     {
         MyTicketCell *cell = (MyTicketCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
         if (cell == nil) {
             NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"MyTicketCell" owner:nil options:nil];
             cell = [array objectAtIndex:0];
             [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
         }
         NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
         if([item[@"merchantTypeID"] intValue]==1 )
         {
             cell.ImageType.image=[UIImage imageNamed:@"icon_food.png"];
         }
         else if([item[@"merchantTypeID"] intValue]==2)
         {
             cell.ImageType.image=[UIImage imageNamed:@"icon_ktv.png"];
         }
         else if ([item[@"merchantTypeID"] intValue]==3)
         {
             cell.ImageType.image=[UIImage imageNamed:@"icon_tea.png"];
         }
         cell.lbMerchantName.text=item[@"merchantName"];
         cell.lbTicketType.text=[NSString stringWithFormat:@"[%@]", item[@"couponTypeName"]];
         cell.lbTicketType.frame=CGRectMake(11, 33, 66, 21);
         [cell.lbTicketType sizeToFit];
         CGRect frame=cell.lbTitle.frame;
         frame.origin.x=cell.lbTicketType.frame.origin.x+cell.lbTicketType.frame.size.width+5;
         cell.lbTitle.frame=frame;
         cell.lbTitle.text=item[@"couponTitle"];
         NSString *endTime=item[@"endDate"];
         cell.lbTime.text=[NSString stringWithFormat:@"有效期：%@",endTime];
         cell.lbCode.text=[NSString stringWithFormat:@"特权码：%@",item[@"couponCode"]];
         cell.lbStatus.text=([item[@"isNotice"] intValue]==1 && [item[@"status"] intValue]==0)?@"即将到期": item[@"statusName"];
         if([cell.lbStatus.text isEqualToString:@"即将到期"])
         {
             [cell.lbStatus setTextColor:[UIColor orangeColor]];
         }
         else
         {
             [cell.lbStatus setTextColor:[UIColor blackColor]];
         }
         cell.lbStatus.hidden=NO;
         return cell;
     }
    else
    {
        LoadMoreCell *cell = (LoadMoreCell *)[tableView dequeueReusableCellWithIdentifier: @"LoadMoreCellIdentifier"];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LoadMoreCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        if(returnCount<pageSize){
            cell.lbText.text=@"";
            cell.hidden = true;
        }else{
            //创建loadMoreCell
            cell.lbText.text=str_more;
        }
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.detailTextLabel.text=@"";
        cell.imageView.image =nil;
        return cell;

    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == [tableDataArray count])
    {
        LoadMoreCell *loadMoreCell=(LoadMoreCell *)[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.lbText.text=str_loading;
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?memberID=%d&password=%@&couponType=%d&status=%d&merchantType=%d&pageIndex=%d",url_myTicketList,[[Config Instance] getMemberId],[[Config Instance] getPassword] ,couponType,status,merchantType,++pageIndex]];
        ASIHTTPRequest *req = [ASIHTTPRequest requestWithURL:url];
        [req setShouldAttemptPersistentConnection:NO];
        [req setDelegate: self];
        [req setDidFinishSelector:@selector(appendTableWith:)];
        [req startAsynchronous];
    }
    else
    {
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        TicketDetailViewController *view=[[TicketDetailViewController alloc] initWithNibName:@"TicketDetailViewController" bundle:nil];
        view.hidesBottomBarWhenPushed=YES;
        view.merchantTypeID=[[item objectForKey:@"merchantTypeID"] intValue];
        view.couponID=[[item objectForKey:@"couponID"] intValue];
        [self.navigationController pushViewController:view animated:YES];
    }
}

-(void) appendTableWith:(ASIHTTPRequest *)request
{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSMutableArray *data = [dic valueForKey:@"data"];
    returnCount = [data count];
    for (int i=0;i<[data count];i++) {
        [tableDataArray addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    if ([data count]==0) {
        [self.TicketTable reloadData];
    }
    //重新调用UITableView的方法, 来生成行.
    [self.TicketTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
   if([indexPath row] < ([tableDataArray count]) && status==0) {
        return YES;
   }
  else
  {
        return NO;
  }
}

- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyTicketCell *cell=(MyTicketCell*)[_TicketTable cellForRowAtIndexPath:indexPath];
    cell.lbStatus.hidden=YES;
}

-(void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyTicketCell *cell=(MyTicketCell*)[_TicketTable cellForRowAtIndexPath:indexPath];
    cell.lbStatus.hidden=NO;

}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?memberID=%d&password=%@&couponMemberID=%d",url_deleteMyTicket,[[Config Instance] getMemberId],[[Config Instance] getPassword] ,[item[@"couponMemberID"] intValue]]];
        ASIHTTPRequest *req = [ASIHTTPRequest requestWithURL:url];
        [req setShouldAttemptPersistentConnection:NO];
        [req startSynchronous];
        NSString *jsonStr = [req responseString];
        NSDictionary *dic = [jsonStr JSONValue];
        if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"])
        {

            [tableDataArray removeObjectAtIndex:indexPath.row];
            // Delete the row from the data source.
            [_TicketTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]  withRowAnimation:UITableViewRowAnimationFade];
        }
        
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)OnBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)OnClickType:(id)sender {
    if(!isShowed){
        selectIndex = 1;
        LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择优惠券类型." options:arrayType fullHeight:100];
        lplv.name = @"arrayType";
        lplv.delegate = self;
        lplv.selectedIndex = couponType;
        [lplv showInView:self.view animated:YES];
        isShowed = true;
    }

}

- (IBAction)OnClickStatus:(id)sender {
    if(!isShowed){
        selectIndex = 2;
        LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择优惠券使用状态" options:arrayStatus fullHeight:200];
        lplv.name = @"arrayStatus";
        lplv.delegate = self;
        lplv.selectedIndex = status;
        [lplv showInView:self.view animated:YES];
        isShowed = true;
    }

}

- (void)leveyPopListView:(LeveyPopListView *)popListView didSelectedIndex:(NSInteger)anIndex options:(NSArray *)_options didSelectedTypeIndex:(NSInteger)anTypeIndex
{
    switch (selectIndex) {
        case 1:{
            _lbType.text = [[arrayType objectAtIndex:anIndex] objectForKey:@"arrayType"];
            couponType=anIndex;
            break;
        }
        case 2:{
            status = anIndex;
            _lbStatus.text = [[arrayStatus objectAtIndex:anIndex] objectForKey:@"arrayStatus"];
            break;
        }
        case 3:
        {
            merchantType=anIndex;
            _lbMerchantType.text=[[arrayMerchantType objectAtIndex:anIndex] objectForKey:@"arrayMerchantType"];
            break;
        }
    }
    pageIndex = 1;
    isShowed = false;
    
    [self getMyTicket];
}
- (void)leveyPopListViewDidCancel
{
    isShowed = false;
}
- (IBAction)OnClickMerchantType:(id)sender {
    if(!isShowed){
        selectIndex =3;
        LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择商户类型" options:arrayMerchantType fullHeight:200];
        lplv.name = @"arrayMerchantType";
        lplv.delegate = self;
        lplv.selectedIndex = merchantType;
        [lplv showInView:self.view animated:YES];
        isShowed = true;
    }

}
@end
